package com.info.zhiduoduo.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.KltPayConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.AesCbcUtil;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.pay.formbean.kltongpay.MerchantFormBean;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.constants.SignType;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.Content;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.Head;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.Request;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.account_info.AccountInfoResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.add_merchant.MerchantContent;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.add_merchant.MerchantRequest;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.add_merchant.MerchantResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.balance_change.BalanceChangeNofity;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.query_merchant.QueryMerchantContent;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.query_merchant.QueryMerchantRequest;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.model.query_merchant.QueryMerchantResult;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.util.HttpUtils;
import com.info.zhiduoduo.pay.sdk.kltongpaysdk.util.RSAUtils;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyMerchantBalanceNotifyRecord;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MerchantService {

	@Autowired
	KltPayConfig kltPayConfig;

	public SmartResult addMerchant(BaseSimpleFormBean<MerchantFormBean> formBean) {

		MerchantFormBean reqdata = formBean.getReqdata();
		//填写默认值
		reqdata.setFullNameEn("-")
				.setNameEn("-")
				.setPriIndustryCode("16")
				.setSecIndustryCode("1611")
				.setThrIndustyCode("10120")
				.setMchtType("1")
				.setBizMchtAttrOrg("99990002")
				.setIncomeAttrOrgId("99990002")
				.setCurrency("156")
				// .setContractBeginDate("-")  选填
				// .setContractEndDate("-")  选填
				.setInvoiceFlag("0")
				.setAdjustState("1")
				.setInOutSplitFlag("0")
				.setRefundStlMode("1")
				.setCustomsDeclareFlag("0")
				.setClearDirectFlag("1")
				.setHomeName("-")
				.setHomeUrl("-")
				.setAddr("-")
				.setLrCertType("1")
				// .setLegalReps("-")
				// .setLrCertNo("-")
				.setIcpNo("-")
				// .setLicenseBeginDate("-")  选填
				// .setLicenseEndDate("-")  选填
				.setOrgRegNo("-")
				// .setOrgRegBeginDate("-")  选填
				// .setOrgRegEndDate("-")  选填
				.setSmealType("0");

		String s = JSON.toJSONString(reqdata);
		System.out.println("s = " + s);

		MerchantContent content = new MerchantContent();
		BeanUtils.copyProperties(reqdata, content);

		//参数
		Head head = new Head();
		head.setMerchantId(kltPayConfig.getMerchantId()).setSignType(SignType.RSA).setVersion("1.0");

		MerchantRequest request = new MerchantRequest(head, content);

		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
		String originStr = jsonObject.toJSONString();
		LogUtil.info("请求参数, 签名前:" + originStr);
		LogUtil.info("md5key=" + kltPayConfig.getMd5Key());
		//添加签名
		// String signStr = SignUtils.addSign(originStr, kltPayConfig.getMd5Key());
		String signStr = null;
		try {
			signStr = RSAUtils.sortAndRsa256Sign(originStr, kltPayConfig.getPrivateKey());
		} catch (Exception e) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}
		LogUtil.info("签名后,请求参数:" + signStr);
		//忽略SSL认证
		String respJsonStr = null;
		try {
			respJsonStr = HttpUtils.sendHttpPostRequest(kltPayConfig.getAddMerchantUrl(), signStr, false);
		} catch (Exception e) {
			e.printStackTrace();
			return SmartResult.fail(e.getMessage());
		}

		LogUtil.info("返回:" + respJsonStr);
		MerchantResult result = JSON.parseObject(respJsonStr, MerchantResult.class);
		if (result == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		} else if (!"000000".equals(result.getResponseCode())) {
			SmartResult smartResult = SmartResult.fail(StatusMsg.StatusMsg_452);
			smartResult.setMsg(result.getResponseMsg());
			return smartResult;
		}
		return SmartResult.success(result);
	}

	public SmartResult queryMerchant(BaseSimpleFormBean<String> formBean) {

		String reqdata = formBean.getReqdata();
		if (reqdata == null) return SmartResult.ofErrorParam();

		Head head = new Head().setSignType(SignType.RSA).setVersion("1.0").setMerchantId(kltPayConfig.getMerchantId());
		QueryMerchantContent content = new QueryMerchantContent(reqdata);
		QueryMerchantRequest request = new QueryMerchantRequest(head, content);

		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
		String originStr = jsonObject.toJSONString();
		LogUtil.info("请求参数, 签名前:" + originStr);
		LogUtil.info("md5key=" + kltPayConfig.getMd5Key());
		//添加签名
		// String signStr = SignUtils.addSign(originSign, kltPayConfig.getMd5Key());
		String signStr = null;
		try {
			signStr = RSAUtils.sortAndRsa256Sign(originStr, kltPayConfig.getPrivateKey());
		} catch (Exception e) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}
		LogUtil.info("签名后,请求参数:" + signStr);
		//忽略SSL认证
		String respJsonStr = null;
		try {
			respJsonStr = HttpUtils.sendHttpPostRequest(kltPayConfig.getQueryMerchantUrl(), signStr, false);
		} catch (Exception e) {
			e.printStackTrace();
			return SmartResult.fail(e.getMessage());
		}

		LogUtil.info("返回:" + respJsonStr);
		QueryMerchantResult result = JSON.parseObject(respJsonStr, QueryMerchantResult.class);
		if (result == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		} else if (!"00000".equals(result.getResponseCode())) {
			SmartResult smartResult = SmartResult.fail(StatusMsg.StatusMsg_199);
			smartResult.setMsg(result.getResponseMsg());
			return smartResult;
		}
		return SmartResult.success(result);
	}

	public SmartResult queryAccountInfo(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();

		if (compid == null) return SmartResult.ofErrorParam();

		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return SmartResult.ofErrorParam();

		String merchantid;
		String md5key;
		String privateKey = "";
		if (StringUtils.isEmpty(account.getMerchantid())) {
			return SmartResult.fail(StatusMsg.StatusMsg_329);
		}

		// 使用企业自己的商户号
		merchantid = account.getMerchantid();
		md5key = account.getMd5key();
		try {
			privateKey = AesCbcUtil.decrypt(account.getMerchantPrivateKey());
		} catch (Exception e) {
			log.error("解析企业商户号的私钥失败", e);
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}

		Head head = new Head().setMerchantId(merchantid).setSignType(SignType.RSA);
		Request request = new Request();
		request.setHead(head);
		request.setContent(new Content());

		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
		String originStr = jsonObject.toJSONString();
		LogUtil.info("请求参数, 签名前:" + originStr);
		LogUtil.info("md5key=" + md5key);
		//添加签名
		String signStr = null;
		try {
			signStr = RSAUtils.sortAndRsa256Sign(originStr, privateKey);
		} catch (Exception e) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		}
		// signStr = SignUtils.addSign(originStr, md5key);
		LogUtil.info("签名后,请求参数:" + signStr);
		//忽略SSL认证
		String respJsonStr = null;
		try {
			respJsonStr = HttpUtils.sendHttpPostRequest(kltPayConfig.getQueryAccountInfoUrl(), signStr, false);
		} catch (Exception e) {
			e.printStackTrace();
			return SmartResult.fail(e.getMessage());
		}

		LogUtil.info("返回:" + respJsonStr);
		AccountInfoResult result = JSON.parseObject(respJsonStr, AccountInfoResult.class);
		if (result == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_199);
		} else if (!"000000".equals(result.getResponseCode())) {
			SmartResult smartResult = SmartResult.fail(StatusMsg.StatusMsg_199);
			smartResult.setMsg(result.getResponseMsg());
			return smartResult;
		}
		return SmartResult.success(result);
	}

	public String balanceChangeNotify(BalanceChangeNofity nofityResult) {

		// 保存通知记录
		CompanyMerchantBalanceNotifyRecord record = new CompanyMerchantBalanceNotifyRecord();
		record.setMerchantid(nofityResult.getMerchantId()).setContent(JSON.toJSONString(nofityResult)).insert();

		String merchantId = nofityResult.getMerchantId();
		List<CompanyAccount> accountList = new CompanyAccount().selectList(Condition.create().eq("merchantid", merchantId));
		if (CollectionUtils.isEmpty(accountList)) {
			log.info("merchantid={}, 没有找到对应的企业,余额变动通知记录失败", merchantId);
			record.setResult(2).updateById();
			return "not found merchant";
		}

		for (CompanyAccount account : accountList) {
			String publicKey;
			try {
				publicKey = AesCbcUtil.decrypt(account.getMerchantPublicKey());
			} catch (Exception e) {
				log.error("商户merchantid={},企业id={},解析公钥,失败.", merchantId, account.getCompid());
				continue;
			}

			boolean checkSign = RSAUtils.checkSign(JSON.toJSONString(nofityResult), publicKey);
			if (!checkSign) {
				record.setResult(1).updateById();
				return "wrong sign!";
			}

		}

		return null;
	}

}
